<?php
namespace app\index\controller;

use think\Controller;
use app\index\controller\IndexBase;
use tree\Tree;

class Goods extends IndexBase
{

    // 无需登陆即可查看的方法列表
    public $except_action = ['detail'];
    // 允许修改的字段
    private $allow_update_field = ['title', 'price', 'area', 'bargain', 'deadline'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 我的二手货页面
     * @author 杨栋森 mutoe@foxmail.com at 2016-07-23
     */
    public function goodsList()
    {
        $param = input('param.');

        $goods = model('Goods');
       /* $goods->where([
            'user_id' => $this->user_id,
            'status' => ['gt', 0], // 过滤审核未通过和已删除的数据
        ]);*/
        $goods->where([
            'user_id' => $this->user_id,
        ]);
        // 分类查看
        $status = @$param['status'];
        switch ($status) {
            case '1':
                $goods->where(['status' => 1]);
                break;
            case '2':
                $goods->where(['status' => 2]);
                break;
            case '3':
                $goods->where('status','in','3,4');
                break;
            case '4':
                $goods->where('status','in','3,4');
                break;
            case '5':
                $goods->where(['status' => 5]);
                break;
            case '-1':
                $goods->where(['status' => -1]);
                break;
            case '0':
                $goods->where(['status' => 0]);
                break;
            default:
                $status = 0;
                $goods->where(['status' => 0]);
                break;
        }
        // 排序规则
        switch (@$param['sort']) {
            case 'deadline':
                $sort = 'deadline';
                $goods->order('deadline');
                break;
            case 'hits':
                $sort = 'hits';
                $goods->order('hits desc');
                break;
            case 'time':
                $sort = 'time';
                $goods->order('create_time desc');
                break;
            default:
                $sort = 'deadline';
                $goods->order('deadline');
        }

        // 分页显示
        $goods_list = $goods->paginate(config('goods.paginate'));
        $href = request()->url(true);
        return view('goods/list', ['data' => $goods_list, 'status' => $status, 'sort' => $sort]);
        //return view('', ['data' => $goods_list, 'sort' => $sort]);
    }

    /**
     * 二手货详情页面 区别显示自己的货物和他人的货物
     * @author 杨栋森 mutoe@foxmail.com at 2016-07-27
     *
     * @param  integer $good_id 二手货编号
     */
    public function detail($good_id = 0)
    {
        if (!$good_id) {
            return $this->redirect('goods/list');
        }

        $goods = model('Goods');
        $data = $goods->where(['good_id' => $good_id])->find();

        // 模型获取器修改了status的值，怎么处理这种情况可以进一步研究
        if ($data->status == '审核未通过' || $data->status == '已删除') {
            return $this->error('该二手货未通过审核或被删除');
        }

        // 点击量自增 (延迟600s写入)
        $goods->where(['good_id' => $good_id])->setInc('hits', 1, 600);

        // 区别显示自己的二手货和他人的二手货展示模版
        $tpl = $data->user_id == $this->user_id ? 'myDetail' : '';
        return view($tpl, ['data' => $data]);

    }

    /**
     * 添加货物
     * @author 杨栋森 mutoe@foxmail.com at 2016-07-20
     *
     * TODO: 整合编辑货物方法
     */
    public function addGoods()
    {
        if (request()->isGet()) {
            $goodscategory = model('GoodsCategory');
            $list = $goodscategory->where('status',1)->field('cate_id as id,parent_id as pid,title,description,status')->select();
            $list = json_decode(json_encode($list),1);
            $tree = new Tree();
            $tree->init($list);
            // 得到第一级菜单
            $first = $tree->getFirst();
            return view('',['category' =>  json_encode($list),'first' => $first]);
        }
        if (request()->isPost()) {
            $data = input('post.');
            // 字段验证
            $validate = validate('Goods');
            if (!$validate->scene('add')->check($data)) {
                return $this->error($validate->getError());
            }

            // 附加提示语
            $extra_message = "";

            // 过滤图片展示字段
            $file_uri_array = [];
            $photo = json_decode($data['photo']);
            unset($data['photo']);
            foreach ($photo as $key => $value) {
                if ($key == "length") {
                    continue;
                }

                // 去除二级根目录前缀
                if ($subroot = config('subroot')) {
                    $foo = explode('/', $subroot);
                    $subroot = array_pop($foo);
                    $value = preg_replace('@/' . $subroot . '@i', '', $value);
                }
                $file_uri_array[] = $value;
            }
            if (!empty($file_uri_array)) {
                // 归档图片
                $new_uri_array = $this->archivePhotos($file_uri_array);
                $error_list = [];
                foreach ($new_uri_array as $key => $new_uri) {
                    if ($new_uri == false) {
                        $error_list[] = $file_uri_array[$key];
                        unset($new_uri_array[$key]);
                    }
                }
                $expand = [
                    'photos' => $new_uri_array,
                    'photos_count' => count($new_uri_array),
                ];
                $data['expand'] = json_encode($expand);

                // 添加第一张图片作为缩略图
                $data['thumb'] = $new_uri_array[0];

                // 如果新数组为空 添加提示语
                if (count($error_list) > 0) {
                    $extra_message .= "，但这些图片好像没有添加上，请返回编辑页面重新添加图片" . $error_list;
                }
            }

            // 数据写入
            $goods = model('Goods');
            $goods->data($data,true);//设置true才会触发修改器
            if (!$goods->allowField(true)->save()) {
                return $this->error($goods->getError());
            }

            // 跳转至货物详情页面
            return $this->success("添加成功" . $extra_message, url('goods/detail', ['good_id' => $goods->good_id]));
        }
    }

    /**
     * 将二手货移入回收站
     * @author 杨栋森 mutoe@foxmail.com at 2016-07-30
     *
     * @param  integer $good_id 要移入回收站货物的id
     * @return ajax_return
     */
    public function recycle($good_id)
    {
        $goods = model('Goods');

        $user_id = $goods->where(['good_id' => $good_id])->value('user_id');
        if ($this->user_id != $user_id) {
            return $this->error("你没有权利这么做");
        }
        // 标记状态
        if (!$goods->save(['status' => 0,'recycle_time' => time()], ['good_id' => $good_id])) {
            return $this->error("删除失败了");
        }
        return $this->success("删除成功，正在返回...", url('goods/goodsList'));

    }

    /**
     * 移除回收站进入卖家下架状态
     * @author cuibo weiai525@outlook.com at 2016-11-10
     * @param  [type] $good_id [description]
     * @return [type]          [description]
     */
    public function outRecycle($good_id)
    {
        $goods = model('Goods');

        $user_id = $goods->where(['good_id' => $good_id])->value('user_id');
        if ($this->user_id != $user_id) {
            return $this->error("你没有权利这么做");
        }
        // 标记状态
        if (!$goods->save(['status' => 3], ['good_id' => $good_id])) {
            return $this->error("操作失败了");
        }
        return $this->success("操作成功，正在返回...", url('goods/goodsList'));

    }

    /**
     * 更新指定字段
     * post数据需按照该格式传入 Object { deadline: "123", good_id: "57" }
     * @author 杨栋森 mutoe@foxmail.com at 2016-07-29
     */
    public function updateField()
    {
        $postdata = input('post.');
        $good_id = $postdata['good_id'];
        unset($postdata['good_id']);
        $goods = model('Goods');

        if (!$goods->where(['good_id' => $good_id])->find()) {
            return $this->error("错误的参数");
        }

        // 验证身份 TODO: 管理员也可通过验证
        $user_id = $goods->where(['good_id' => $good_id])->value('user_id');
        if ($this->user_id != $user_id) {
            return $this->error("你没有权利这么做");
        }

        // 验证字段
        $validate = validate('Goods');
        $validate->scene('update', array_keys($postdata));
        if (!$validate->scene('update')->check($postdata)) {
            return $this->error($validate->getError());
        }

        // 过滤字段
        $savedata = [];
        foreach ($postdata as $key => $value) {
            if (in_array($key, $this->allow_update_field)) {
                $savedata[$key] = $value;
            }
        }

        $result = $goods->save($savedata, ['good_id' => $good_id]);
        if (!$result) {
            return $this->error('数据保存出错');
        }

        return $this->success('保存成功');

    }

    /**
     * 设置缩略图
     * 要求get方法 且传入的缩略图路径必须存在于已上传的图片列表中
     * @author 杨栋森 mutoe@foxmail.com at 2016-07-31
     *
     * @param  integer  $good_id    需替换缩略图的货物id
     * @param  string   $uri        缩略图资源路径
     * @return ajax_return
     */
    public function setThumb($good_id, $uri)
    {
        $goods = model('Goods');

        // 权限检查
        $user_id = $goods->where(['good_id' => $good_id])->value('user_id');
        if ($user_id != $this->user_id) {
            return $this->error("你没有权利这么做");
        }

        // 有效性检查
        $expand = json_decode($goods->where(['good_id' => $good_id])->value('expand'));
        if (!in_array($uri, $expand->photos)) {
            return $this->error("你必须从已上传的图片中选一张作为缩略图");
        }

        // 保存数据
        if (!$goods->save(['thumb' => $uri], ['good_id' => $good_id])) {
            return $this->error($goods->getError());
        }

        return $this->success();
    }

    /**
     * 追加图片
     * 需使用post方法
     * @author 杨栋森 mutoe@foxmail.com at 2016-07-31
     *
     * @param   integer $good_id    需要追加到货物的id
     * @param   string  $uri        json格式的uri数组
     * @return  ajax_return
     */
    public function addPhotos()
    {
        $good_id = input('post.good_id');
        $goods = model('Goods');
        if (!$goods->where(['good_id' => $good_id])->find()) {
            return $this->error('参数错误');
        }
        $imguri = input('post.uri');

        // 过滤图片展示字段
        $file_uri_array = [];
        $photo = json_decode($imguri, true);
        unset($photo['length']);
        foreach ($photo as $key => $value) {
            // 去除二级根目录前缀
            if ($subroot = config('subroot')) {
                $value = preg_replace('@' . $subroot . '@i', '', $value);
            }
            $file_uri_array[] = $value;
        }
        if (empty($file_uri_array)) {
            return $this->error('没有待上传的图片');
        }

        // 归档图片
        $new_uri_array = $this->archivePhotos($file_uri_array);
        $error_list = [];
        foreach ($new_uri_array as $key => $new_uri) {
            if ($new_uri == false) {
                $error_list[] = $file_uri_array[$key];
                unset($new_uri_array[$key]);
            }
        }

        // 合并图片字段
        $expand = json_decode($goods->where(['good_id' => $good_id])->value('expand'), true);
        if (empty($expand)) {
            $final_array = $new_uri_array;
        }else{
            $final_array = array_merge($expand['photos'], $new_uri_array);
        }

        // 注意expand中可能含有其他字段，只操作需要操作的字段即可
        $expand['photos'] = $final_array;
        $expand['photos_count'] = count($final_array);
        if (!$goods->save(['expand' => json_encode($expand)], ['good_id' => $good_id])) {
            return $this->error('数据写入失败');
        }

        // 如果新数组为空 添加提示语
        $extra_message = '';
        if (count($error_list) > 0) {
            $extra_message .= "，但这些图片好像没有添加上，请返回编辑页面重新添加图片" . $error_list;
        }

        return $this->success('添加成功' . $extra_message);

    }

    /**
     * 删除图片
     * 需使用post方法
     * @author 杨栋森 mutoe@foxmail.com at 2016-07-31
     *
     * @param  integer  $good_id    需要操作的货物id
     * @param  string   $uri        需要删除的图片的地址
     * @return ajax_return
     */
    public function removePhoto()
    {
        $good_id = input('post.good_id');
        $goods = model('Goods');
        $expand = json_decode($goods->where(['good_id' => $good_id])->value('expand'));

        // 移除该图片
        $uri = input('post.uri');
        $key = array_search($uri, $expand->photos);
        if ($key === false) {
            return $this->error('不存在该图片');
        }
        array_splice($expand->photos, $key, 1);
        $expand->photos_count--;

        // 如果删除的图片是缩略图，同时移除缩略图
        $thumb = $goods->where(['good_id' => $good_id])->value('thumb');
        if ($thumb == $uri) {
            $savedata['thumb'] = null;
        }

        // 写入数据库
        $savedata['expand'] = json_encode($expand);
        if (!$goods->save($savedata, ['good_id' => $good_id])) {
            return $this->error('删除失败');
        }

        // 移除该图片
        if (!$this->deletePhoto($uri)) {
            // 文件未成功移除 TODO: 写入log
            return $this->success('删除成功');
        }

        return $this->success('删除成功');

    }

    /**
     * 归档图片
     * 按月份将货物展示图片归档
     * @author 杨栋森 mutoe@foxmail.com at 2016-07-21
     *
     * @param  array  $file_uri_array   图片相对路径数组(相对web根目录)
     * @return array  返回结果路径数组(相对web根目录) 空文件返回null, 移动失败返回false
     */
    private function archivePhotos($file_uri_array)
    {
        $result = [];
        // 获取存储目录
        $target_path = config('upload_path.photo');
        // 获取当前月份
        $month = date('Ym', time());
        foreach ($file_uri_array as $file_uri) {
            // 如果是空值 在返回结果中插入null
            if (empty($file_uri)) {
                $result[] = null;
                continue;
            }

            // 生成12位摘要文件名
            $new_name = substr(md5(time() . $file_uri), 0, 12);
            // 取得文件后缀
            $foo = explode(".", $file_uri);
            $ext = array_pop($foo);
            $new_name .= '.' . $ext;

            // 建立归档文件夹
            $root = dirname($_SERVER['SCRIPT_FILENAME']);
            $new_path = $target_path . "/" . $month;
            $real_path = $root . $new_path;
            if (!file_exists($real_path)) {
                mkdir($real_path);
            }

            // 检查源文件是否存在
            if (!file_exists($root . $file_uri)) {
                $result[] = false;
                continue;
            }

            // 移动文件
            if (rename($root . $file_uri, $real_path . "/" . $new_name)) {
                $result[] = $new_path . "/" . $new_name;
            } else {
                $result[] = false;
            }
        }
        return $result;
    }

    /**
     * 移除图片的文件
     * @author 杨栋森 mutoe@foxmail.com at 2016-07-31
     *
     * @param  string $file_uri 图片的资源路径
     * @return boolean
     */
    private function deletePhoto($file_uri)
    {
        // 获取根目录路径
        $root = dirname($_SERVER['SCRIPT_FILENAME']);

        // 检查源文件是否存在
        if (!file_exists($root . $file_uri)) {
            return false;
        }

        // 移除文件
        unlink($root . $file_uri);
        return true;
    }
    /**
     * 用户下架物品 post
     * @author cuibo weiai525@outlook.com at 2016-11-09
     * @param  integer $good_id 物品id
     * @return ajax_return          
     */
    public function notSell($good_id)
    {
        $good_id = input('post.good_id');
        $goods = model('Goods');
        if (!$goods->where(['good_id' => $good_id])->find()) {
            return $this->error("错误的参数");
        }
        $data = $goods->where(['good_id' => $good_id])->find();
        if ($this->user_id != $data->user_id) {
            return $this->error("你没有权利这么做");
        }
        if ($data->getData('status') != 1) {
            return $this->error("只能下架在出售的商品");
        }

        $result = $goods->save(['status' => 3], ['good_id' => $good_id]);
        if (!$result) {
            return $this->error('数据保存出错');
        }
        return $this->success('下架成功');
    }

    /**
     * 用户上架物品 post
     * @author cuibo weiai525@outlook.com at 2016-11-09
     * @param  integer $good_id 物品id
     * @return ajax_return          
     */
    public function sell($good_id)
    {
        $good_id = input('post.good_id');
        $goods = model('Goods');
        if (!$goods->where(['good_id' => $good_id])->find()) {
            return $this->error("错误的参数");
        }
        $data = $goods->where(['good_id' => $good_id])->find();
        if ($this->user_id != $data->user_id) {
            return $this->error("你没有权利这么做");
        }
        if ($data->getData('status') != 3 && $data->getData('status') != 4) {
            return $this->error("只有处于下架中的商品才能上架哟");
        }

        $result = $goods->save(['status' => 1], ['good_id' => $good_id]);
        if (!$result) {
            return $this->error('数据保存出错');
        }
        return $this->success('上架成功');
    }

}
